﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.AIT.OpenAPIBE;
using UFIDA.U9.Base;
using UFIDA.U9.Base.UserRole;
using UFIDA.U9.CBO.Pub.Controller;
using UFSoft.UBF.Business;
using UFSoft.UBF.Util.Context;

namespace ufida.u9.ait.openapi.utils
{
    class U9Utils
    {
        const string filepath = "RestServices/ufida.u9.ait.openapi.IHelloSV.svc";
        static DateTime fileTime = DateTime.MinValue;
        const int days = 62;
        //是否做有效性检查
        static readonly bool IsCheck = false;

        static U9Utils()
        {
            U9Utils.fileTime = FileUtils.GetFileTime(System.IO.Path.Combine(U9Utils.GetU9Dir(), filepath));
        }

        public static String GetU9Dir()
        {
            return System.AppDomain.CurrentDomain.BaseDirectory;
        }
        public static ContextDTOData CreateContext()
        {

            User user = User.Finder.FindByID(Context.LoginUserID);
            if(user == null)
            {
                throw new Exception("查找用户失败!");
            }

            ContextDTOData retdto = new ContextDTOData
            {
                CultureName = PlatformContext.Current.Culture,
                EntCode = PlatformContext.Current.EnterpriseID,
                OrgCode = Context.LoginOrg.Code,
                OrgID = Context.LoginOrg.ID,
                UserCode = user.Code,//这里传入用户编码
                UserID = Convert.ToInt64(Context.LoginUserID)
            };
            return retdto;
        }

        public static bool IsValid()
        {
            if (IsCheck == false)
                return true;
            else if (fileTime.AddDays(days) > DateTime.Now)
                return true;
            else
                return false;
        }

        public static void DBLog(object method, object indata, ResultDTOData retdto)
        {
            using(ISession session = Session.Open())
            {
                AITLog logbe = AITLog.Create();
                logbe.Code = method.GetType().Name;
                logbe.Name = method.GetType().Name;
                if (indata != null)
                {
                    string json = JsonConvert.SerializeObject(indata);
                    logbe.InParm = json;
                }
                if (retdto != null)
                {
                    string json = JsonConvert.SerializeObject(retdto);
                    logbe.OutParm = json;
                }
                logbe.RetCode = retdto.Code;
                logbe.RetMsg = retdto.Msg;

                session.Commit();
            }
        }
    }
}
